package com.mimosa.common.message;

import java.io.File;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mimosa.common.dao.HibernateDao;
import com.mimosa.common.service.CommonService;
import com.mimosa.common.system.user.UserContext;
import com.mimosa.util.config.Page;
import com.mimosa.util.config.YesNoType;
import com.mimosa.util.constant.StringConstUtil;

/**
 * 站内消息接口实现类
 * 
 * @author Mr.bai
 * 
 */

@Service
@Transactional
public class MessageService extends CommonService<TSiteMessage, String> {
	@Resource
	private TSiteMessageDao siteMessageDao;
	@Resource
	private TMessageReceiverDao messageReceiverDao;
	@Resource
	private TMessageReplyDao messageReplyDao;
	@Resource
	private TMessageAttachmentDao messageAttachmentDao;
	// @Resource
	// private EmailService emailService;

	@Resource
	private UserContext userContext;

	/**
	 * 发送站内信，科委通知服务
	 * 
	 * @param tMessagereply
	 *            封装好的站内信息类
	 * @return 成功返回true，失败返回false
	 */
	public boolean send(TSiteMessage siteMessage) {
		siteMessageDao.save(siteMessage);
		return true;
	}

	/**
	 * 发送工作流相关的消息和邮件(siteMessage对象请参阅receiverUserSetting方法
	 * 
	 * @param siteMessage
	 */
	public void sendStreamMessage(String title, String content, String... receiverUserIds) {
		TSiteMessage siteMessage = new TSiteMessage();
		siteMessage.setSendUser("1");
		siteMessage.setTitle(title);
		siteMessage.setContent(content);
		siteMessage.setSendUserName("System");
		siteMessage.setMessageType(MessageType.MESSAGE.ordinal());
		siteMessage.setSendDate(new Date());
		// 消息接收信息
		if (receiverUserIds != null) {
			Set<TMessageReceiver> set = new HashSet<TMessageReceiver>();
			Date date = new Date();
			for (String rid : receiverUserIds) {
				TMessageReceiver messageReceiver = new TMessageReceiver();
				messageReceiver.setReadStatus(YesNoType.N.name());
				messageReceiver.setCreateTime(date);
				messageReceiver.setLastUpdateTime(date);
				messageReceiver.setLastUpdateUserId("1");
				messageReceiver.setReceiverUserId(rid);
				messageReceiver
						.setId(UUID.randomUUID().toString().replace(StringConstUtil.MINUS, StringConstUtil.EMPTY));
				messageReceiver.setSiteMessage(siteMessage);

				set.add(messageReceiver);
			}
			// 设置消息与接收者之间的关联信息
			siteMessage.settMessageReceiver(set);
		}
		super.saveEntity(siteMessage);
	}

	/**
	 * 查看所有已发站内信息服务
	 * 
	 * @return 封装好的站内信息对象的 集合
	 */
	public List<TMessageReceiver> findAll(String column, String messageType) {
		return messageReceiverDao.findBy(column, messageType);
	}

	/**
	 * 根据用户ID查找所有收到站内信
	 * 
	 * @param column
	 *            数据库表的字段
	 * @param ReceiverId
	 *            对应字段值
	 * @return 封装好的收到信息的对象的集合
	 */
	public List<Object> findAndPage(String hql, int pageSize, int pageNo) {
		return messageReceiverDao.page(hql, pageSize, pageNo);
	}

	/**
	 * 回复站内信息
	 * 
	 * @param messageReply
	 *            封装好的回复信息的对象
	 * @return
	 */
	public boolean reply(TMessageReply messageReply) {
		messageReplyDao.save(messageReply);
		return true;
	}

	/**
	 * 取得信息总数
	 * 
	 * @return 总数
	 */
	public int findcount() {
		return siteMessageDao.getCount(YesNoType.N.name(), userContext.currentUserId(), MessageType.MESSAGE.ordinal());
	}

	/**
	 * findCount:(获取消息的数量). <br/>
	 *
	 * @author Administrator
	 * @param status
	 *            消息的状态
	 * @param userId
	 *            用户的标识
	 * @param messageType
	 *            消息的尖型
	 * @return
	 * @since JDK 1.7
	 */
	public int findCount(String status, String userId, Integer messageType) {
		return siteMessageDao.getCount(status, userId, messageType);
	}

	/**
	 * 科委通知分页查找
	 * 
	 * @param hql
	 * @param pageSize
	 * @param pageNo
	 * @return
	 */
	public Page<TSiteMessage> findNotice(Page<TSiteMessage> page, String column, int messageType) {
		page.setOrder("DESC");
		page.setOrderBy("sendDate");
		Criterion relation1 = Restrictions.eq(column, messageType);
		return siteMessageDao.findPage(page, relation1);
	}

	/**
	 * 修改科委通知
	 */
	public void modifyNotice(TSiteMessage siteMessage) {
		TSiteMessage temp = siteMessageDao.get(siteMessage.getId());
		if (siteMessage.getMessageAttachment() == null) {
			siteMessage.setMessageAttachment(temp.getMessageAttachment());
		} else if (temp.getMessageAttachment().size() != 0) {
			for (TMessageAttachment ma : temp.getMessageAttachment()) {
				TMessageAttachment tma = new TMessageAttachment();
				tma = siteMessage.getMessageAttachment().iterator().next();
				tma.setId(ma.getId());
				tma.setSiteMessage(siteMessage);
				FileUtils.deleteQuietly(new File(ma.getFilePath()));
			}
		}
		siteMessageDao.getSession().merge(siteMessage);
	}

	/**
	 * 删除科委通知
	 * 
	 * @param siteMessage
	 */
	public void delNotice(TSiteMessage siteMessage, String rootPath) {
		siteMessage = siteMessageDao.get(siteMessage.getId());
		Set<TMessageAttachment> set = siteMessage.getMessageAttachment();
		for (TMessageAttachment ma : set) {
			FileUtils.deleteQuietly(new File(rootPath + ma.getFilePath()));
		}
		siteMessageDao.delete(siteMessage);
	}

	/**
	 * 更新阅读状态
	 * 
	 * @param messageReceiver
	 */
	public TMessageReceiver modifyReceiverReadState(TMessageReceiver messageReceiver) {
		TMessageReceiver mr = messageReceiverDao.get(messageReceiver.getId());
		mr.setReadStatus(YesNoType.Y.name());
		mr.setReadTime(new Date());
		messageReceiverDao.save(mr);
		return mr;
	}

	/**
	 * 查找站内消息
	 * 
	 * @param pageSize
	 * @param pageNo
	 * @param column
	 * @param messageType
	 * @return
	 */
	public Page<TMessageReceiver> findMessage(Page<TMessageReceiver> page, String column, String messageType) {
		String hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and m." + column
				+ "='" + messageType + "' and s.messageFlag = 0 order by s.sendDate desc";
		return messageReceiverDao.findPage(page, hql);
	}

	/**
	 * 查找用户的收件信息
	 * 
	 * @param page
	 *            分页展示对象
	 * @param filters
	 *            过滤条件，包括消息类型，用户身份，消息标题等
	 * @return
	 */
	public Page<TMessageReceiver> findReceiveMessage(Page<TMessageReceiver> page, Integer msgType, String readStatus,
			String userId, String msgTitle, String projectId) {
		return this.messageReceiverDao.findReceiveMessage(page, msgType, readStatus, userId, msgTitle, projectId);
	}

	public Page<TMessageReceiver> findMessage(Page<TMessageReceiver> page, String column, String messageType,
			String column1, int type1) {
		String hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and " + column
				+ "='" + messageType + "' and " + column1 + "=" + type1
				+ " and s.messageFlag = 0 order by s.sendDate desc";
		return messageReceiverDao.findPage(page, hql);
	}

	public Page<TMessageReceiver> findMessage(Page<TMessageReceiver> page, String column, String messageType,
			String column1, String date) {
		String hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and m.receiverUserId='"
				+ userContext.currentUserId() + "' and to_char(s.sendDate,'yyyymmdd')=" + date.substring(0, 4)
				+ date.substring(5, 7) + date.substring(8) + " and s.messageFlag = 0 order by s.sendDate desc";
		return messageReceiverDao.findPage(page, hql);
	}

	public Page<TMessageReceiver> findMessage(Page<TMessageReceiver> page, String column, String messageType,
			String column1, String date, String column2, int type2) {
		String hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and m.receiverUserId='"
				+ userContext.currentUserId() + "' and m.readStatus = " + type2 + " and to_char(s.sendDate,'yyyymmdd')="
				+ date.substring(0, 4) + date.substring(5, 7) + date.substring(8)
				+ " and s.messageFlag = 0 order by s.sendDate desc";
		return messageReceiverDao.findPage(page, hql);
	}

	public TSiteMessage getNotice(TSiteMessage siteMessage) {
		return siteMessageDao.get(siteMessage.getId());
	}

	public Page<TMessageReceiver> findProjectMessage(Page<TMessageReceiver> page, String projectId) {
		String hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and m.receiverUserId='"
				+ userContext.currentUserId() + "' and s.projectId = '" + projectId
				+ "' and s.messageFlag = 0 order by s.sendDate desc";
		return page = messageReceiverDao.findPage(page, hql);
	}

	/**
	 * 查找意见反馈
	 * 
	 * @param pageSize
	 * @param pageNo
	 * @param column
	 * @param messageType
	 * @param column1
	 * @param type1
	 * @return
	 */
	public Page<TMessageReceiver> findAdminMessage(Page<TMessageReceiver> page) {
		String hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and receiverUserId = '1' and s.messageFlag != 0";
		/*
		 * Criterion relation1 = Restrictions.eq(column, messageType); Criterion
		 * relation2 = Restrictions.not(Restrictions.eq("messageFlag",0));
		 */
		return messageReceiverDao.findPage(page, hql);
	}

	/**
	 * 查找所有有附件的科委通知
	 * 
	 * @param page
	 * @return
	 */
	public Page<TMessageAttachment> findNoticeByPic(Page<TMessageAttachment> page) {
		String hql = "select m from TMessageAttachment m ,TSiteMessage s where m.tSiteMessage.id = s.id and s.messageType="
				+ MessageType.NOTICE.ordinal() + "  order by s.sendDate desc";
		return messageAttachmentDao.findPage(page, hql);
	}

	/**
	 * 搜索消息
	 * 
	 * @param pageSize
	 * @param pageNo
	 * @param column
	 * @param messageType
	 * @return
	 */
	public Page<TMessageReceiver> searchMessage(Page<TMessageReceiver> page, String column, String value,
			String keyWords, int type) {
		String hql;
		if (type != 1) {
			hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and m." + column
					+ "='" + value + "' and s.messageFlag = 0 and s.messageType ='" + type + "' and s.title like '%"
					+ keyWords + "%' order by s.sendDate desc";
		} else {
			hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and m." + column
					+ "='" + value + "' and s.messageFlag = 0 and s.title like '%" + keyWords
					+ "%' order by s.sendDate desc";
		}
		return messageReceiverDao.findPage(page, hql);
	}

	public Page<TMessageReceiver> searchSnsMessage(Page<TMessageReceiver> page, String column, String value,
			String projectId) {
		String hql = "select m from TMessageReceiver m ,TSiteMessage s where m.siteMessage.id = s.id and m." + column
				+ "='" + value + "' and s.messageFlag = 0 and s.projectId ='" + projectId + "'order by s.sendDate desc";
		return page = messageReceiverDao.findPage(page, hql);
	}

	/**
	 * 根据收信ID，获得消息内容
	 * 
	 * @param messageReceiver
	 * @return
	 */
	public TMessageReceiver getMessageById(TMessageReceiver messageReceiver) {
		return messageReceiverDao.get(messageReceiver.getId());
	}

	public TMessageAttachment getAttachEntity(TMessageAttachment entity) {
		return messageAttachmentDao.get(entity.getId());
	}

	@Override
	protected HibernateDao<TSiteMessage, String> getHibernateDao() {
		return this.siteMessageDao;
	}
}